package server.core.util;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import communication.exception.AuthenticationException;

import server.core.base.User;
import server.core.dao.MemoryDAO;

public class Authentication {
	protected Authentication(){}
	public static class SingletonHolder {
		public static final Authentication instance = new Authentication();
	}
	public static Authentication getInstance() {
		return SingletonHolder.instance;
	}
	
	private Set<User> CurrentUsers=new HashSet<User>();
	public Set<User> getCurrentUsers() {
		return CurrentUsers;
	}
	public void setCurrentUsers(Set<User> currentUsers) {
		CurrentUsers = currentUsers;
	}
	
	/**
	 * @param name
	 * @param password
	 * @throws AuthenticationException 
	 */
	public User signup(String name, String password) throws AuthenticationException {
		User user=null;
		Set<?> entrySet = MemoryDAO.INSTANCE
				.getEntityMap(User.class).entrySet();
		Iterator<Map.Entry<Long, User>> itr = (Iterator<Entry<Long, User>>) entrySet.iterator();
		while (itr.hasNext()) {
			Entry<Long, User> x = itr.next();
			if (name.equals(x.getValue().getName())
					& password.equals(x.getValue().getPassword())){
				getCurrentUsers().add(x.getValue());
				user = x.getValue();
			}
		}
		if(user==null)
			throw new AuthenticationException("Uncorrect name and/or password");
		else
			return user;
	}
	
}
